package com.itheima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.mapper.WmUserMapper;


import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>自媒体用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Override
    public WmUser getByApUserId(Integer apUserId) {
        /**
         * 通过app用户Id获取自媒体账号
         * @param apUserId
         * @return
         */
            return query().eq("ap_user_id", apUserId).one();
        }

    @Override
    public Map<String,Object> loginCheck( Map<String, String> loginParams) {

        //1.获取参数据
        String name = loginParams.get("name");
        String password = loginParams.get("password");


        //2.参数非空校验
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            //空就报错
            throw  new LeadNewsException("用户名或者密码错误");
        }
        //3.通过登录查询用户信息
        WmUser wmUserName = query().eq("name", name).one();
        if (wmUserName == null){

            throw new LeadNewsException("用户名或者密码错误");
        }

        //4.密码校验

        //4.1密码加盐
        password += wmUserName.getSalt();
        String encryptepwd = DigestUtils.md5DigestAsHex(password.getBytes());

        //4.2校验密码是否相同，不同报错
        if (!wmUserName.getPassword().equals(encryptepwd)){
            throw new LeadNewsException("用户名或者密码错误");
         }

        //5.校验密码是是否相同不同则报错
        String token = AppJwtUtil.createToken(wmUserName.getId().longValue());


        //6.构建结构并返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", wmUserName);
        return result;
        //7.
        //8.



    }

}
